<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.username"
        size="small"
        placeholder="用户名"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.nickname"
        size="small"
        placeholder="昵称"
        style="width: 200px;margin-left:2%"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <p style="display:inline-block;margin-left:2%">县域：</p>
      <el-input
        v-model="listQuery.county"
        size="small"
        placeholder="管理员权限填写有效"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        size="small"
        class="filter-item"
        type="success"
        icon="el-icon-search"
        @click="handleFilter"
      >搜索</el-button>
      <el-button
        size="small"
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >添加</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      size="small"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column
        :class-name="getSortClass('id')"
        label="ID"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="APP账户"
        width="250px"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="姓名"
        width="150px"
        align="center"
      >
        <template slot-scope="{ row }">
          <span>{{ row.nickname }}</span>
          <!-- <el-tag>{{ row.type | typeFilter }}</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column
        label="地址"
        min-width="110px"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.address }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="showReviewer"
        label="Reviewer"
        width="110px"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.reviewer }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="县域"
        width="150px"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.county }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="联络员"
        align="center"
        width="95px"
      >
        <template slot-scope="{ row }">
          <span>{{ row.countlly }}</span>
          <!-- <span v-else>0</span> -->
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="300"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button
            size="small"
            align="center"
            type="primary"
            @click="handleUpdate(row)"
          >编辑</el-button>
          <el-button
            type="success"
            plain
            size="small"
            @click="handleLiaison(row)"
          >详情 + 联络员</el-button>
          <!-- <el-button
            v-if="row.status != 'deleted'"
            size="mini"
            type="danger"
            @click="handleModifyStatus(row, 'deleted')"
          >
            Delete
          </el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.start"
      :limit.sync="listQuery.length"
      @pagination="getList"
    />

    <el-dialog
      :close-on-click-modal="false"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      append-to-body
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="150px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="用户名">
          <el-input v-model="temp.username" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="temp.nickname" />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="temp.idcard" />
        </el-form-item>
        <el-form-item
          style="width:800px"
          label="地址"
        >
          <v-distpicker
            :province="temp.province"
            :city="temp.city"
            :area="temp.county"
            @selected="select"
          />
        </el-form-item>
        <el-form-item label="详细地址">
          <el-input v-model="temp.address" />
        </el-form-item>
        <el-form-item label="建档立卡贫困户号">
          <el-input
            :disabled="dialogStatus == 'create' ? false : true"
            v-model="temp.poornumbercard"
          />
        </el-form-item>
        <el-form-item label="银行卡号">
          <el-input v-model="temp.bankcard" />
        </el-form-item>
        <el-form-item label="银行卡开户行">
          <el-input v-model="temp.openbank" />
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >确定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="outerVisible"
      append-to-body
      title="详情信息"
      width="80%"
    >
      <el-form
        :model="liaUserList"
        label-position="left"
        style="margin-left:50px;"
      >
        <el-form-item
          label-width="60px"
          style="float:left; width:33%"
          label="姓名:"
        >
          <span>{{ liaUserList.nickname }}</span>
        </el-form-item>
        <el-form-item
          label-width="100px"
          style="float:left;width:33%"
          label="身份证号："
        >
          <span>{{ liaUserList.idcard }}</span>
        </el-form-item>
        <el-form-item
          label-width="60px"
          style="float:left;width:33%"
          label="地址："
        >
          <span>{{ liaUserList.address }}</span>
        </el-form-item>
        <el-form-item
          label-width="150px"
          style="float:left;width:33%"
          label="建档立卡贫困户："
        >
          <span>{{ liaUserList.poornumbercard }}</span>
        </el-form-item>
        <el-form-item
          label-width="120px"
          style="float:left;width:33%"
          label="银行卡号："
        >
          <span>{{ liaUserList.bankcard }}</span>
        </el-form-item>
        <el-form-item
          label-width="120px"
          style="width:33%"
          label="银行卡开户行："
        >
          <span>{{ liaUserList.openbank }}</span>
        </el-form-item>
      </el-form>
      <span style="display:block; width:100%; height:1px; background:#E5E5E5;" />
      <div
        class="filter-container"
        style="margin-top:2%;"
      >
        <el-button
          size="small"
          class="filter-item"
          style="float:right"
          type="success"
          icon="el-icon-edit"
          @click="handleLly()"
        >添加</el-button>
      </div>
      <el-table
        v-loading="listLoading"
        :key="tableKey"
        :data="liaUser"
        size="small"
        border
        fit
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column
          label="APP账户"
          width="350px"
          align="center"
        >
          <template slot-scope="{ row }">
            <span>{{ row.username }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="姓名"
          width="250px"
          align="center"
        >
          <template slot-scope="{ row }">
            <span>{{ row.nickname }}</span>
            <!-- <el-tag>{{ row.type | typeFilter }}</el-tag> -->
          </template>
        </el-table-column>
        <el-table-column
          label="性别"
          width="350px"
          align="center"
        >
          <template slot-scope="{ row }">
            <span>{{ row.sex == null ? "" : row.sex == 1 ? "男" : "女" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          min-width="300"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="{ row }">
            <el-button
              size="small"
              align="center"
              type="primary"
              @click="deleteLiaison(row)"
            >解绑联络员</el-button>
            <!-- <el-button
            v-if="row.status != 'deleted'"
            size="mini"
            type="danger"
            @click="handleModifyStatus(row, 'deleted')"
          >
            Delete
            </el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        :visible.sync="innerVisible"
        :close-on-click-modal="false"
        width="60%"
        title="设置绑定联络员"
        append-to-body
      >
        <div class="filter-container">
          <el-input
            v-model="LlyLiatQuery.username"
            size="small"
            placeholder="用户名"
            style="width: 200px;"
            class="filter-item"
            @keyup.enter.native="handleLly"
          />
          <el-input
            v-model="LlyLiatQuery.nickname"
            size="small"
            placeholder="昵称"
            style="width: 200px;margin-left:2%"
            class="filter-item"
            @keyup.enter.native="handleLly"
          />
          <el-button
            size="small"
            class="filter-item"
            type="success"
            icon="el-icon-search"
            @click="handleLly"
          >搜索</el-button>
        </div>
        <el-table
          v-loading="listLoading"
          ref="multipleTable"
          :key="tableKey"
          :data="allLlyList"
          size="small"
          border
          fit
          highlight-current-row
          tooltip-effect="dark"
          style="width: 100%;"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="55"
          />
          <el-table-column
            label="APP账户"
            min-width="300px"
            align="center"
          >
            <template slot-scope="{ row }">
              <span>{{ row.username }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="姓名"
            width="300px"
            align="center"
          >
            <template slot-scope="{ row }">
              <span>{{ row.nickname }}</span>
              <!-- <el-tag>{{ row.type | typeFilter }}</el-tag> -->
            </template>
          </el-table-column>
          <el-table-column
            label="性别"
            width="300px"
            align="center"
          >
            <template slot-scope="{ row }">
              <span>{{ row.sex == null ? "" : row.sex == 1 ? "男" : "女" }}</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="llyTotal > 0"
          :total="llyTotal"
          :page.sync="LlyLiatQuery.start"
          :limit.sync="LlyLiatQuery.length"
          @pagination="handleLly"
        />
        <div
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="innerVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handlesaveBindLLy()"
          >确定</el-button>
        </div>
      </el-dialog>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="refreshList()">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, createEmanager, updateEmanager } from '@/api/article' // waves directive
import {
  Edetails,
  EdetailsList,
  untyingLia,
  llyList,
  yzgRelCount,
  addLly
} from '@/api/appUser'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 0, display_name: '无效' },
  { key: 1, display_name: '正常' },
  { key: 2, display_name: '锁定' }
]
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      liaUserList: {},
      multipleSelection: [],
      delliaName: '',
      liaUser: null,
      total: 0,
      listLoading: true,
      allLlyList: null,
      listQuery: {
        start: 1,
        length: 10,
        username: '',
        nickname: '',
        sort: '+id'
      },
      LlyLiatQuery: {
        start: 1,
        length: 10,
        username: '',
        nickname: '',
        county: ''
      },
      llyTotal: 0,
      llyCount: 0,
      addLlyList: [],
      outerVisible: false,
      sortOptions: [
        { label: 'ID Ascending', key: '+id' },
        { label: 'ID Descending', key: '-id' }
      ],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      innerVisible: false,
      temp: {
        id: undefined,
        provinceCode: '',
        cityCode: '',
        countyCode: '',
        province: '',
        city: '',
        county: '',
        approle: ''
      },
      dialogFormVisible: false,
      liaUserName: '',
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      rules: {
        type: [
          { required: true, message: 'type is required', trigger: 'change' }
        ],
        // timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [
          { required: true, message: 'title is required', trigger: 'blur' }
        ]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    refreshList() {
      this.outerVisible = false
      this.getList()
    },
    handleSelectionChange(val) {
      console.info(val)
      this.multipleSelection = val
    },
    handleLly() {
      this.innerVisible = true
      console.log(this.liaUserList.username)
      var params = {
        pageConvert: true,
        start: this.LlyLiatQuery.start,
        length: this.LlyLiatQuery.length,
        county: this.liaUserList.county,
        username: this.LlyLiatQuery.username,
        nickname: this.LlyLiatQuery.nickname
      }
      llyList(params).then(res => {
        this.allLlyList = res.data
        this.llyTotal = res.recordsTotal
        console.log(this.llyTotal)
      })
      yzgRelCount(this.liaUserList.username).then(res => {
        this.llyCount = res
        console.log(this.llyCount)
      })
    },
    handlesaveBindLLy() {
      if (this.llyCount >= 5) {
        this.$notify({
          title: '警告',
          message: '绑定的联络员超出限制，请先解绑',
          type: 'warning'
        })
      } else {
        var checkedTotal = this.multipleSelection.length
        if (checkedTotal + this.llyCount > 5) {
          this.$notify({
            title: '警告',
            message: '选中联络员数量过多',
            type: 'warning'
          })
        } else if (checkedTotal < 1) {
          this.$notify({
            title: '警告',
            message: '请选择联络员',
            type: 'warning'
          })
        } else {
          this.multipleSelection.forEach(item => {
            this.addLlyList.push(item.username)
          })
          var params = {
            llyname: this.addLlyList,
            yzgname: this.liaUserList.username,
            nickname: this.liaUserList.nickname
          }
          addLly(params).then(res => {
            if (res.code === '200') {
              this.$notify({
                title: '提示',
                message: '添加联络员成功',
                type: 'success'
              })
              this.innerVisible = false
              EdetailsList(this.liaUserName).then(res => {
                this.liaUser = res.data
              })
            } else {
              this.$notify({
                title: '警告',
                message: '系统异常，请联系管理员',
                type: 'danger'
              })
            }
          })
        }
      }
      this.multipleSelection = []
    },
    deleteLiaison(row) {
      this.delliaName = row.username
      this.$confirm('确认解绑该联络员?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          untyingLia(this.delliaName).then(res => {
            if (res.code === '200') {
              this.$message({
                type: 'success',
                message: '解绑成功!'
              })
              EdetailsList(this.liaUserName).then(res => {
                this.liaUser = res.data
              })
            } else {
              this.$message({
                type: 'danger',
                message: '系统异常，请联系管理员!'
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消解绑'
          })
        })
    },
    handleLiaison(row) {
      this.outerVisible = true
      this.liaUserName = row.username
      Edetails(this.liaUserName).then(res => {
        this.liaUserList = res.data
      })
      EdetailsList(this.liaUserName).then(res => {
        this.liaUser = res.data
      })
    },
    select: function(data) {
      this.temp.provinceCode = data.province.code
      this.temp.cityCode = data.city.code
      this.temp.countyCode = data.area.code
      this.temp.province = data.province.value
      this.temp.city = data.city.value
      this.temp.county = data.area.value
    },
    getList() {
      this.listLoading = true
      var params = {
        pageConvert: true,
        start: this.listQuery.start,
        length: this.listQuery.length,
        username: this.listQuery.username,
        nickname: this.listQuery.nickname,
        county: this.listQuery.county
      }
      fetchList(params).then(response => {
        this.list = response.data
        console.log(this.list)
        this.total = response.recordsTotal
        console.log(this.total)
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.start = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined
        // importance: 1,
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.temp.approle = '0'
          createEmanager(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
      this.getList()
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      // this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          // tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateEmanager(tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
      this.getList()
    },
    handleDelete(row) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}`
        ? 'ascending'
        : sort === `-${key}`
          ? 'descending'
          : ''
    }
  }
}
</script>
